package manager.image;


import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Set;

import javax.imageio.ImageIO;

public class ImageManager
{
	/**
	 * Hashtable ID/Image of all the images which should be painted in the current screen (facing right)
	 */
	private Hashtable<String, BufferedImage> images = new Hashtable<String, BufferedImage>();
	/**
	 * Singleton instance
	 */
	private static ImageManager instance;
	
	/**
	 * Singleton
	 * @return the instance of the Singleton
	 */
	public static ImageManager getInstance()
	{
		if (instance == null)
			instance = new ImageManager();

		return instance;
	}
	
	/**
	 * Reset the buffer by loading images from a list of ID/Images path
	 * @param toLoad ID/Image path of all the images which should be painted in the current screen
	 */
	public void reset(Hashtable<String, String> toLoad)
	{
		//Clear loaded images and collect the garbage
		images.clear();
		System.gc();
		
		Set<String> keys = toLoad.keySet();
		BufferedImage img = null;
		
		for (String key : keys) {
			
			try {
				img = ImageIO.read(new File(key));
			} catch (IOException e) {
				System.out.println("Failed to load image : "+key);
				e.printStackTrace();
			}
			images.put(key, img);
		}
	}
	
	/**
	 * Get the image stored under the given name (ID)
	 * @param name The ID of the image to load
	 * @return the image stored under the given name (ID)
	 */
	public BufferedImage getImage(String name) {
			return images.get(name);
	}
}
